package com.gdcnano.nanoamp.media.sound.playlist
{
	import mx.collections.ArrayCollection;
	import mx.utils.StringUtil;
	
    
    
    public class M3UPlaylist extends AbstractPlaylist
    {
        private static var TRACK_DELIMITER:String = "\r\n";
        
        
		public override function setPlaylistData(data:Object):Boolean
		{
			var playlist:String = data as String;
			var tracksLocationCollection:Array = playlist.toString().split(TRACK_DELIMITER);
			if (tracksLocationCollection.length > 0)
			{
				createPlaylist(tracksLocationCollection);
				return true;
			}
			else
			{
				return false;
			}
		}
		
        
        /**
         * Creates playlist collection
         * 
         * for test porposes let's decide that m3u playlist is generated
         * from the root of iTunes structured media library
         * so stored in M3U playlist file paths will be formed in that way:
         * %artist%/%album%/%track title%
         * 
         * @param tracksLocationCollection
         */
        private function createPlaylist(tracksLocationCollection:Array):void
        {
            var pathDelimiter:String = "\\";
            _tracklist = new ArrayCollection();
            for each (var trackLocation:String in tracksLocationCollection)
            {
                // Check if track location row is not empty
                if (StringUtil.trim(trackLocation) != "")
                {
                    var track:Track = new Track();
                    var spliTrackInfo:Array = trackLocation.split(pathDelimiter);
                    
                    // Support only predefined playlist structure
                    if (spliTrackInfo.length != 3)
                    {
                        throw new ArgumentError("Supporting of M3UPlaylist was added only for the test porposes. Please see comment on M3UPlaylist.createPLaylist()");
                    }
                    track.location = trackLocation;
                    track.artist = spliTrackInfo[0];
                    track.album = spliTrackInfo[1];
                    track.name = spliTrackInfo[2];
                    
                    _tracklist.addItem(track);
                }
            }
        }
    }
}